from fresh.utils.utils import *
import random
from ..myModels.userModel import *
from django.forms import model_to_dict
import re  # 需要引用re模块

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework.decorators import api_view
from rest_framework.response import Response 

@api_view(['get'])
def user_all(request):
    return info('全部用户')

@api_view(['get'])
def user_add(request):
    return info('添加用户')

@api_view(['get'])
def user_get_code(request):
    phone = get_param(request, 'phone')
    if not phone:
        return fail('缺少手机号码')

    code = ''
    for i in range(4):
        code += str(random.randint(0, 9))
    user = User.objects.filter(phone=phone).first()
    # 存在就更新code, 不存在就创建
    if user:
        user.phone = phone
        user.sms_code = code
        user.save()
    else:
        User.objects.create(phone=phone, sms_code=code)
    res_data = {"sms_code": code, "phone": phone}
    return success(res_data)

@api_view(['post'])
def user_login(request):
    phone = get_param(request, 'phone')
    sms_code = get_param(request, 'smsCode')
    if not phone:
        return fail('手机号码不能为空')
    if not sms_code:
        return fail('验证码不能为空')
    # ^ 表示从什么开始（^1表示从1开始） \d表示0~9之间的数字   {10}表示出现次数为10位$结束
    result = re.match('^1\d{10}$', phone)
    if not result:
        return fail('手机号码不合法')

    user = User.objects.filter(phone=phone, sms_code=sms_code).first()
    if not user:
        return fail('验证码不正确')
    else:
        session = request.session.get('session')
        print(session)
        request.session['session'] = user.id
        # request.session.set_expiry()
        res = model_to_dict(user)
        return success(res)

@api_view(['get'])
def user_logout(request):
    return success('退出成功')
